package com.ton.common.controller.task;

import com.kypj.frame.common.EmptyUtil;
import com.ton.common.entity.TonPayOrder;
import com.ton.common.service.PayOrderService;
import com.ton.config.NetContext;
import com.ton.utils.http.RestTemplateUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;

@Slf4j
public class PayOrderTrans {
    @Getter
    @Setter
    private TonPayOrder tonPayOrder;

    @Getter
    @Setter
    private long executetime; // 过期时间

    @Getter
    private boolean syncMoneyWorking;

    public static PayOrderTrans createFrom(TonPayOrder order) {
        PayOrderTrans trans = new PayOrderTrans();
        trans.tonPayOrder = order;
        return trans;
    }

    //判断是否过期
    public boolean isListenTimeOut(long now) {  // 10分钟支付
        return now - tonPayOrder.getCreateTime().getTime() > 1000L * 60 * 10;
    }


    public Long getOrderId() {
        return tonPayOrder.getId();
    }


    /**
     * 订单监听事件
     *
     * @param tonPayOrder
     */
    public synchronized void listenTans(TonPayOrder tonPayOrder) {
        try {
            syncMoneyWorking = true;
//            if (EmptyUtil.isEmpty(tonPayOrder.getAddress())) {
//                return;
//            }
            System.out.println("正在继续监听----->>" + System.currentTimeMillis());
            Long balanceTrx = 0L;
            Long balanceTrc20 = 0L;
//            TrxUtils trxUtils = NetContext.getInstance(TrxUtils.class);
//            TrcUtils trcUtils = NetContext.getInstance(TrcUtils.class);
            //TRX查询逻辑
            if (tonPayOrder.getCoinType() == 0) {
                //balanceTrx = trxUtils.searchTrxBalance(payOrder.getAddress(), payOrder.getPrivateKey());
                //log.info("比较金额---->>"+aLong+"||"+ payOrder.getAmount());
                //1TRX = 1000000
                if (balanceTrx >= tonPayOrder.getTargetAmount()) {
                    this.orderCompletion(tonPayOrder, 0, balanceTrx, 0L);
                } else {
                    //待删除
                    this.orderCompletion(tonPayOrder, 0, balanceTrx, 0L);
                    //log.info("等待支付----->> " + tonPayOrder.getAddress() + " 当前余额:" + balanceTrx);
                }
            } else {
                //TRC20查询逻辑
                //balanceTrc20 = trcUtils.searchTRC20Balance(payOrder.getPrivateKey(), payOrder.getAddress());
                if (balanceTrc20 >= tonPayOrder.getTargetAmount()) {
                    this.orderCompletion(tonPayOrder, 0, 0L, balanceTrc20);
                } else {
                    //待删除
                    this.orderCompletion(tonPayOrder, 0, 0L, balanceTrc20);
                    //log.info("等待支付----->> " + tonPayOrder.getAddress() + " 当前余额:" + balanceTrc20);
                }
            }
        } catch (Exception e) {
            log.error("支付监听异常！", e);
        } finally {
            executetime = System.currentTimeMillis() + PayOrderPayingTask.ORDER_QUERY_WAIT_TIME;
            syncMoneyWorking = false;
        }
    }

    /**
     * 订单完成的调用 方法
     *
     * @param tonPayOrder     订单对象
     * @param coinType     收款类型
     * @param balanceTrx   trx
     * @param balanceTrc20 trc
     */
    public void orderCompletion(TonPayOrder tonPayOrder, Integer coinType, Long balanceTrx, Long balanceTrc20) {

        PayOrderService payOrderService = NetContext.getInstance(PayOrderService.class);
        //TronAccountService tronAccountService = NetContext.getInstance(TronAccountService.class);

        //返回数据
        log.info("完成订单!----->>" + tonPayOrder.getAmount());

        payOrderService.updateCompletionStatus(tonPayOrder, balanceTrx, balanceTrc20);

        //调用回调地址.....
        callbackUrl(tonPayOrder);

        //更新任务
        //.....
        PayOrderPayingTask.deleteOrder(tonPayOrder.getId()); //移除任务
    }


    /**
     * 成功回调
     *
     * @param tonPayOrder 订单
     */
    public void callbackUrl(TonPayOrder tonPayOrder) {
        if (tonPayOrder.getCallbackUrl().contains("http")) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("orderId", tonPayOrder.getId()); //商户订单号
            params.put("merchantOrderId", tonPayOrder.getMerchantOrderId()); //商家订单号
            params.put("amount", tonPayOrder.getAmount()); //支付金额
            params.put("appId", tonPayOrder.getAppId()); //appid
            params.put("bankMsg", ""); //信息
            params.put("time", new Date().getTime()); //订单创建时间
            params.put("coinType", tonPayOrder.getCoinType()); //货币类型
            params.put("remark", tonPayOrder.getRemark()); //备注
            params.put("status", 2); //成功
            if (tonPayOrder.getStatus() == 1) { //支付完成
                params.put("status", 2);
            }
            String doPost = RestTemplateUtils.doPost(tonPayOrder.getCallbackUrl(), new HashMap<>(), params);

            //握手验证
            if (doPost.equals("FAIL")) {
                new Thread(() -> {
                    try {
                        Thread.sleep(2000);
                        String reDoPost = RestTemplateUtils.doPost(tonPayOrder.getCallbackUrl(), new HashMap<>(), params);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                });
                
            }

            log.info("完成支付回调！！");
        }
    }


}
